import folderIcon from "@/assets/icons/folder.svg?component";
import picIcon from "@/assets/icons/pic.svg?component";
import musicIcon from "@/assets/icons/music.svg?component";
import videoIcon from "@/assets/icons/video.svg?component";
import archIcon from "@/assets/icons/arch.svg?component";
import fileIcon from "@/assets/icons/file.svg?component";
import { Status, type Task } from "@/stores/apis";
import type { StyleValue } from "vue";

const picExt = new Set([
  "jpg",
  "jpeg",
  "png",
  "gif",
  "bmp",
  "tiff",
  "webp",
  "svg",
]);

const musicExt = new Set([
  "mp3",
  "wav",
  "flac",
  "aac",
  "ogg",
  "wma",
  "aiff",
  "alac",
]);

const videoExt = new Set(["mp4", "avi", "mkv", "mov", "wmv", "flv", "webm"]);

const archExt = new Set(["zip", "rar", "7z", "tar", "gz", "bz2"]);

function getExIcon(name: string, mode?: string) {
  if (mode === "multi") {
    return folderIcon;
  }
  const last = name.lastIndexOf(".");
  if (last < 0) {
    return fileIcon;
  }
  const ext = name.slice(last + 1);
  if (picExt.has(ext)) {
    return picIcon;
  }
  if (musicExt.has(ext)) {
    return musicIcon;
  }
  if (videoExt.has(ext)) {
    return videoIcon;
  }
  if (archExt.has(ext)) {
    return archIcon;
  }
  return fileIcon;
}

function getTaskTag(status: Status): {
  color: string;
  content: string;
} {
  switch (status) {
    case Status.Waiting:
      return { color: "volcano", content: "等待中" };
    case Status.Active:
      return { color: "processing", content: "进行中" };
    case Status.Pause:
      return { color: "warning", content: "已暂停" };
    case Status.Seeding:
      return { color: "blue", content: "做种中" };
    case Status.Complete:
      return { color: "success", content: "已完成" };
    case Status.Error:
      return { color: "red", content: "出错了" };
  }
}

function getSpeed(t: Task) {
  const speed = t.seeder ? t.upload_speed : t.download_speed;
  if (speed < 1024) {
    return `${speed} B/s`;
  } else if (speed < 1024 * 1024) {
    return `${(speed / 1024).toFixed(2)} KB/s`;
  } else if (speed < 1024 * 1024 * 1024) {
    return `${(speed / 1024 / 1024).toFixed(2)} MB/s`;
  } else {
    return `${(speed / 1024 / 1024 / 1024).toFixed(2)} GB/s`;
  }
}

function getReadableSize(size: number): string {
  if (size < 1024) {
    return `${size}B`;
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(2)} KB`;
  } else if (size < 1024 * 1024 * 1024) {
    return `${(size / 1024 / 1024).toFixed(2)} MB`;
  } else {
    return `${(size / 1024 / 1024 / 1024).toFixed(2)} GB`;
  }
}

function btnStyle(main: string, outline: string): StyleValue {
  return {
    backgroundColor: main,
    borderColor: main,
    outlineColor: outline,
  };
}

export { getExIcon, getTaskTag, getSpeed, getReadableSize, btnStyle };
